package com.runfast.common.config;

import com.runfast.common.security.spring.*;
import com.runfast.common.service.RunfastCuserService;
import com.runfast.common.service.RunfastLoginRecordService;
import com.runfast.common.utils.JsonUtils;
import com.runfast.common.web.entity.Result;
import com.runfast.common.web.entity.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.savedrequest.NullRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author: lijin
 * @date: 2018年06月01日
 */
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private RunfastCuserService cuserService;

    @Autowired
    private RunfastLoginRecordService loginRecordService;


    @Bean
    public AuthenticationProvider mobilePasswordAuthenticationProvider() {
        return new MobilePasswordAuthenticationProvider(cuserService);
    }

    @Bean
    public AuthenticationProvider mobileSmsCodeAuthenticationProvider() {
        return new MobileSmsCodeAuthenticationProvider(cuserService);
    }

    @Bean
    public AuthenticationProvider thirdAuthenticationProvider() {
        return new ThirdAuthenticationProvider(cuserService);
    }

    @Bean
    public ProviderManager authenticationManager(List<AuthenticationProvider> authenticationProviders) {
        return new ProviderManager(authenticationProviders);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(mobilePasswordAuthenticationProvider())
                .authenticationProvider(mobileSmsCodeAuthenticationProvider())
                .authenticationProvider(thirdAuthenticationProvider());
    }

    /*@Override
    protected void configure(HttpSecurity http) throws Exception {

        JWTAuthenticationFilter jwtAuthenticationFilter = new JWTAuthenticationFilter(authenticationManager());
        jwtAuthenticationFilter.setCuserService(cuserService);

        JWTLoginFilter jwtLoginFilter = new JWTLoginFilter();
        jwtLoginFilter.setAuthenticationManager(authenticationManager());
        jwtLoginFilter.setFilterProcessesUrl("/api/user/account/login");
        jwtLoginFilter.setAuthenticationSuccessHandler((request, response, authentication) -> request.getRequestDispatcher("/api/user/account/login/success").forward(request, response));
        jwtLoginFilter.setAuthenticationFailureHandler(new AuthenticationFailureHandler() {
            @Override
            public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
                Result fail = Result.fail(ResultCode.FAIL, exception.getLocalizedMessage());
                String respStr = JsonUtils.getMapper().writeValueAsString(fail);

                response.setContentType("application/json;charset=UTF-8;");
                PrintWriter writer = response.getWriter();
                writer.println(respStr);
                writer.flush();
            }
        });

        LogoutTokenHandler logoutTokenHandler = new LogoutTokenHandler();
        logoutTokenHandler.setCuserService(cuserService);
        logoutTokenHandler.setLoginRecordService(loginRecordService);

        HttpSessionSecurityContextRepository securityContextRepository = new HttpSessionSecurityContextRepository();
        securityContextRepository.setAllowSessionCreation(false);
        http.setSharedObject(RequestCache.class, new NullRequestCache());
                http
                .securityContext().securityContextRepository(securityContextRepository)
                .and()
                .exceptionHandling()
                .accessDeniedHandler((request, response, accessDeniedException) -> request.getRequestDispatcher("/api/user/account/unauthencated").forward(request,response)).authenticationEntryPoint(new TokenAuthenticationEntryPoint("/api/user/account/unauthencated"))
                .and()
                .addFilter(jwtLoginFilter)
                .addFilterAt(jwtAuthenticationFilter,BasicAuthenticationFilter.class)
                .cors().disable()
                .csrf().disable()
                .authorizeRequests().antMatchers(
                        "/api/user/account/register",
                        "/api/user/account/registerAndBind",
                        "/api/user/account/loginByPwd",
                        "/api/user/account/loginBySms",
                        "/api/user/account/loginByThird",
                        "/api/user/account/mobileExist",
                        "/api/user/wm/home/agent",
                        "/api/user/wm/home/businessNearBy",
                        "/api/user/wm/home/page",
                        "/api/user/wm/home/search",
                        "/api/user/wm/home/zoneBusiness",
                        "/api/user/wm/home/offZoneMore",
                        "/api/user/wm/home/businessType",
                        "/api/user/wm/home/offZoneMoreBusiness",
                        "/api/user/wm/business/detail",
                        "/api/user/wm/business/listComment",
                        "/api/user/wm/goods/search",
                        "/api/user/wm/goods/catalogs",
                        "/api/user/wm/my/businessJoin",
                        "/api/user/wm/my/driverJoin",
                        "/api/user/wm/my/cityAgentJoin",
                        "/api/user/wm/my/custom",
                        "/api/user/wm/my/sendSms",
                        "/api/user/wm/my/checkVersion",
                        "/api/user/wm/my/updatePwdBySmsCode",
                "/upload/*.jpg"

                ).permitAll()
                .anyRequest().authenticated()
                .and()
                .logout().logoutUrl("/api/user/account/logout").permitAll()
                .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

                        request.getRequestDispatcher("/api/user/account/logout/success").forward(request, response);
                    }
                })
                .addLogoutHandler(logoutTokenHandler);
    }*/

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        JWTAuthenticationFilter jwtAuthenticationFilter = new JWTAuthenticationFilter(authenticationManager());
        jwtAuthenticationFilter.setCuserService(cuserService);

        LogoutTokenHandler logoutTokenHandler = new LogoutTokenHandler();
        logoutTokenHandler.setCuserService(cuserService);
        logoutTokenHandler.setLoginRecordService(loginRecordService);

        HttpSessionSecurityContextRepository securityContextRepository = new HttpSessionSecurityContextRepository();
        securityContextRepository.setAllowSessionCreation(false);

        http.setSharedObject(RequestCache.class, new NullRequestCache());
        http
                .securityContext().securityContextRepository(securityContextRepository)
                .and()
                .exceptionHandling().authenticationEntryPoint((request, response, authException) -> {
                    Result fail = Result.fail(ResultCode.ACCOUNT_RELOGIN);
                    String respStr = JsonUtils.getMapper().writeValueAsString(fail);

                    response.setContentType("application/json;charset=UTF-8;");
                    PrintWriter writer = response.getWriter();
                    writer.println(respStr);
                    writer.flush();
                })
                .accessDeniedHandler((request, response, accessDeniedException) -> {
                    Result fail = Result.fail(ResultCode.NO_AUTHORIZED);
                    String respStr = JsonUtils.getMapper().writeValueAsString(fail);

                    response.setContentType("application/json;charset=UTF-8;");
                    PrintWriter writer = response.getWriter();
                    writer.println(respStr);
                    writer.flush();
                })
                .and()
                .addFilterAt(jwtAuthenticationFilter, BasicAuthenticationFilter.class)
                .cors().disable()
                .csrf().disable()
                .formLogin().disable()
                .requestCache().disable()
                .headers().disable()
                .httpBasic().disable()
                .authorizeRequests().antMatchers(
                "/api/user/account/login",
                "/api/user/account/register",
                "/api/user/account/registerAndBind",
                "/api/user/account/loginByPwd",
                "/api/user/account/loginBySms",
                "/api/user/account/loginByThird",
                "/api/user/account/mobileExist",
                "/api/user/account/miniLogin",
                "/api/user/account/verifySmsCode",
                "/api/user/home/driverCountNearBy",
                "/api/user/home/baseDeliveryFee",
                "/api/user/wm/home/agent",
                "/api/user/wm/home/businessNearBy",
                "/api/user/wm/home/page",
                "/api/user/wm/home/search",
                "/api/user/wm/home/fullLessZoneBusiness",
                "/api/user/wm/home/fullFreeZoneBusiness",
                "/api/user/wm/home/freePartZoneBusiness",
                "/api/user/wm/home/businessType",
                "/api/user/wm/home/offZoneMoreBusiness",
                "/api/user/wm/home/businessSubTypes",
                "/api/user/wm/business/detail",
                "/api/user/wm/business/listComment",
                "/api/user/wm/goods/search",
                "/api/user/wm/goods/catalogs",
                "/api/user/wm/my/businessJoin",
                "/api/user/wm/my/driverJoin",
                "/api/user/wm/my/cityAgentJoin",
                "/api/user/wm/my/custom",
                "/api/user/wm/my/sendSms",
                "/api/user/wm/my/checkVersion",
                "/api/user/wm/my/updatePwdBySmsCode",
                "/api/user/wm/cart/add",
                "/api/user/wm/cart/delete",
                "/api/user/wm/cart/clear",
                "/upload/*.jpg"

        ).permitAll()
                .anyRequest().authenticated()
                .and()
                .logout().logoutUrl("/api/user/account/logout").permitAll()
                .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

                        request.getRequestDispatcher("/api/user/account/logout/success").forward(request, response);
                    }
                })
                .addLogoutHandler(logoutTokenHandler);
    }
}
